//
//  EasyTakePicViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/9/27.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "EasyTakePicViewController.h"

#import "EasyTakePicDetailViewController.h"
#import "AddrChooserViewController.h"
#import "EasyTakePicPublishViewController.h"
#import "OptionsPresentViewController.h"
#import "MHNavigationController.h"

#import "SSPPublishContentCell.h"

@interface EasyTakePicViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) EasyTakePicViewModel* viewModel;

// UI
//@property (nonatomic, strong) UILabel* _addressLabel;
//@property (nonatomic, strong) UIButton* _addressButton;

//IBOutlet
@property (nonatomic, weak) IBOutlet UIView* choosersView;
@property (nonatomic, weak) IBOutlet UIButton* publishTypeChooserBtn;
@property (nonatomic, weak) IBOutlet UIButton* zoneChooserBtn;
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;

@end

@implementation EasyTakePicViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = SUGlobalGrayBackgroundColor;
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    // tableView auto rowHeight
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100.0f;
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[SSPPublishContentCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
//    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x)
//     {
//         @strongify(self)
//
//     }];
}

- (void)initUI
{
    @weakify(self);
    
    if (!self.viewModel.isMyself)
    {
        UIView* titleView = [[UIView alloc] init];
        
        UIImageView* titleImgView = [[UIImageView alloc] initWithImage:MHImageNamed(@"zi_stxd")];
        titleImgView.contentMode = UIViewContentModeScaleAspectFit;
        
        UILabel* titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"（随手拍）";
        titleLabel.font = [UIFont systemFontOfSize:16.0f];
        
        [titleView addSubview:titleImgView];
        [titleView addSubview:titleLabel];
        
        [titleImgView mas_remakeConstraints:^(MASConstraintMaker *make)
         {
             make.right.mas_equalTo(titleLabel.mas_left).mas_offset(4);
             make.top.mas_equalTo(0);
             make.bottom.mas_equalTo(0);
             make.left.mas_equalTo(0);
         }];
        
        [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make)
         {
             make.left.mas_equalTo(titleImgView.mas_right).mas_offset(4);
             make.right.mas_equalTo(0);
             make.top.mas_equalTo(0);
             make.bottom.mas_equalTo(0);
         }];
        
        titleView.frame = (CGRect) {0, 8, 136, 36};
        self.navigationItem.titleView = titleView;
        
        UIButton* myPublishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [myPublishBtn setTitle:@"我的发表" forState:UIControlStateNormal];
        [myPublishBtn setTitleColor:UIColorHex(#929292) forState:UIControlStateNormal];
        myPublishBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        myPublishBtn.frame = (CGRect) {0, 0, 64.0f, 44.0f};
        [myPublishBtn addTarget:self action:@selector(_onBtnMyPublish) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myPublishBtn];
        
//        UIView* cityView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 0, 64}];
//
//        UILabel* cityLabel = [[UILabel alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
//        cityLabel.text = @"全国 >";
//        cityLabel.textColor = Color_MainGreen;
//        cityLabel.font = [UIFont systemFontOfSize:14.0f];
//        cityLabel.textAlignment = NSTextAlignmentRight;
//        [cityView addSubview:cityLabel];
//
//        UIImageView* cityArrowImg = [[UIImageView alloc] initWithFrame:(CGRect) {0, 12, 22, 27}];
//        cityArrowImg.image = [UIImage imageNamed:@"icon_location"];
//        cityArrowImg.contentMode = UIViewContentModeCenter;
//        [cityView addSubview:cityArrowImg];
//
//        UIButton* cityBtn = [[UIButton alloc] initWithFrame:(CGRect) {0, 0, 0, 44}];
//        [[cityBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
//         {
//             @strongify(self);
//
//             [self _push2AddrPop];
//         }];
//        [cityView addSubview:cityBtn];
//
//        [cityLabel mas_remakeConstraints:^(MASConstraintMaker *make)
//         {
//             make.height.mas_equalTo(44);
//
//             make.left.mas_equalTo(cityArrowImg.mas_right);
//             make.top.mas_equalTo(0);
//             make.bottom.mas_equalTo(0);
//             make.right.mas_equalTo(0);
//         }];
//
//        [cityArrowImg mas_remakeConstraints:^(MASConstraintMaker *make)
//         {
//             make.height.mas_equalTo(22);
//             make.width.mas_equalTo(27);
//
//             make.left.mas_equalTo(0);
//             make.right.mas_equalTo(cityLabel.mas_left).mas_offset(0);
//             make.top.mas_equalTo(0);
//             make.bottom.mas_equalTo(0);
//         }];
//
//        [cityBtn mas_remakeConstraints:^(MASConstraintMaker *make)
//         {
//             make.left.mas_equalTo(0);
//             make.right.mas_equalTo(0);
//             make.top.mas_equalTo(0);
//             make.bottom.mas_equalTo(0);
//         }];
//
//        [cityView mas_remakeConstraints:^(MASConstraintMaker *make)
//         {
//             make.height.mas_equalTo(64);
//         }];
//
//        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:cityView];
//        self.navigationItem.rightBarButtonItem = rightItem;
//        self._addressLabel = cityLabel;
//        self._addressButton = cityBtn;
        
        self.tabBarItem.title = @"随手拍";
        
        self.tabBarItem.image = [[UIImage imageNamed:@"tabbar_takepic"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tabbar_takepic_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    DataManager* dm = [DataManager sharedDataManager];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [self rac_signalForSelector:@selector(viewWillAppear:)];
    RACSignal* didAppearSignal = [self rac_signalForSelector:@selector(viewDidAppear:)];
    RACSignal* viewDidLayoutSVSignal = [self rac_signalForSelector:@selector(viewDidLayoutSubviews)];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [didAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x)
     {
         @strongify(self)
         
     }];
    
    [[[viewDidLayoutSVSignal take:1] deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self)
         
         //重置 更新 frame
         [self _setupAllView];
     }];
    
#pragma mark -- bindViewModel
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    self.viewModel.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self);
        
        [self.viewModel.showDetailCmd execute:indexPath];
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
        {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    [[self.viewModel.showDetailCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2EasyTakePicDetailVC:x];
    }];
    
    if (![self.viewModel.reqUserID isNotBlank])
    {
        RACSignal* addressChangeSignal = [RACObserve(self.viewModel, zone) distinctUntilChanged];
        [[addressChangeSignal replay] subscribeNext:^(id x)
        {
            @strongify(self);

            self.zoneChooserBtn.titleLabel.text = x;
            [self.zoneChooserBtn setTitle:x forState:UIControlStateNormal];
        }];
        
        [[self.zoneChooserBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
         {
             @strongify(self);
             
             [self _push2AddrPop];
         }];
        
        RACSignal* publishTitleChangeSignal = [RACObserve(self.viewModel, publishTitle) distinctUntilChanged];
        [[publishTitleChangeSignal replay] subscribeNext:^(id x)
         {
             @strongify(self);
             
             self.publishTypeChooserBtn.titleLabel.text = x;
             [self.publishTypeChooserBtn setTitle:x forState:UIControlStateNormal];
         }];
        
        [[self.publishTypeChooserBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x)
         {
             @strongify(self);
             
             [self _present2PublishTypeChooser];
         }];
    }
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 更新初始化 操作
- (void)_setupSubViews
{
    
}

- (void)_setupAllView
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    for (NSLayoutConstraint* constraint in self.choosersView.constraints)
    {
        if (constraint.firstAttribute == NSLayoutAttributeHeight)
        {
            constraint.constant = [self.viewModel.reqUserID isNotBlank] ? 44.0f : 0.0f;
            
            break;
        }
    }
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

- (void)_onBtnMyPublish
{
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    if ([um isLogined])
    {
        EasyTakePicPublishViewModel* vm = [[EasyTakePicPublishViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"生态行动（随手拍）"}];
        EasyTakePicPublishViewController* vc = [[EasyTakePicPublishViewController alloc] initWithViewModel:vm];
        
        MHNavigationController* navc = [[MHNavigationController alloc] initWithRootViewController:vc];
        
        [[UIViewController getCurrentVC] presentViewController:navc animated:NO completion:^{
            
        }];
    }
    else
    {
        [MBProgressHUD mh_showTips:@"请登录后再操作"];
    }
}

#pragma mark - Delegate 一些无法用RAC实现
// UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

//// 下拉刷新
- (void)tableViewDidTriggerHeaderRefresh{
    /// 先调用父类的加载数据
    [super tableViewDidTriggerHeaderRefresh];
}
/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SSPPublishContentCell class])];
}

/// config  data
- (void)configureCell:(SSPPublishContentCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(SSPPublishContentItemViewModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

/// 文本内容区域
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsZero;
}

#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
//    /// 所以笔者采用实现计算好的cell的高度
//
//    return [self.viewModel.dataSource[indexPath.row] cellHeight];
//}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

#pragma mark-代理方法
// 设立实现代理，注意要返回UIModalPresentationNone
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller
{
    return UIModalPresentationNone;
}

#pragma mark - 功能

#pragma mark - 跳转
- (void)_present2PublishTypeChooser
{
    OptionsPresentViewController* vc = nil;
    
    NSArray* titles = self.viewModel.publishTypeTitles;
    
    @weakify(self);
    // 测试更多弹出
    OptionsPresentViewModel* vm = [[OptionsPresentViewModel alloc] initWithParams:@{}];
    vm.titles = titles;
    vm.topTitle = @"发布类型";
    vm.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                    {
                        @strongify(self);
                        
                        NSIndexPath* indexPath = input;
                        
                        [self.viewModel resetPublishType:indexPath.row];
                        
                        [[UIViewController getCurrentVC] dismissViewControllerAnimated:vc completion:^{
                            
                        }];
                        
                        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                            
                            [subscriber sendCompleted];
                            
                            return nil;
                        }];
                    }];
    vc = [[OptionsPresentViewController alloc] initWithViewModel:vm];
    vc.view.backgroundColor = [UIColor clearColor];
    //         vc.modalPresentationStyle = UIModalPresentationOverCurrentContext|UIModalPresentationFullScreen;
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        vc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }else{
        vc.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    [[UIViewController getCurrentVC] presentViewController:vc animated:YES completion:^
     {
         vc.view.backgroundColor = UIColorHex(#0000000f);
     }];
}

- (void)_push2AddrPop
{
    DataManager* dm = [DataManager sharedDataManager];
    
    @weakify(self)
    AddrChooserViewModel* vm = [[AddrChooserViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"选择地区"}];
    vm.chooseBlock = ^(ProvinceListData* choosePData)
    {
        @strongify(self);
        
        [self.viewModel resetZoneData:choosePData];
    };
    AddrChooserViewController* vc = [[AddrChooserViewController alloc] initWithViewModel:vm];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)_push2EasyTakePicDetailVC:(NSDictionary*)info
{
    SSPListData* listData = info[@"List"];
    SSPDetailData* detailData = info[@"Detail"];
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    EasyTakePicDetailViewModel* vm = [[EasyTakePicDetailViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"详情", @"SSPListData":listData, @"SSPDetailData":detailData}];
    vm.isCtrl = [um isLogined];
    vm.isMyself = self.viewModel.isMyself;
    EasyTakePicDetailViewController* vc = [[EasyTakePicDetailViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    @weakify(self);
    [[RACObserve(vm, isNeedListRefresh) takeUntil:[vc rac_willDeallocSignal]] subscribeNext:^(id x)
    {
        @strongify(self);
        
        BOOL isNeedListRefresh = [x boolValue];
        
        if (isNeedListRefresh)
        {
            [self.viewModel.requestRemoteDataCommand execute:@0];
        }
    }];
}

@end


